package com.avcompris.util;

import static com.avcompris.util.ExceptionUtils.nonNullArgument;

import java.io.File;

import javax.xml.transform.Source;
import javax.xml.transform.TransformerException;
import javax.xml.transform.URIResolver;
import javax.xml.transform.stream.StreamSource;

/**
 * implementation of {@link URIResolver} that points to the file system.
 * 
 * @author David Andriana Copyright Avantage Compris SARL 2008-2009 ©
 */
public class XsltFileURIResolver implements URIResolver {

	/**
	 * the original XSLT file.
	 */
	private final File xsltFile;

	/**
	 * constructor.
	 * 
	 * @param xsltFile the original XSLT file
	 */
	public XsltFileURIResolver(final File xsltFile) {

		this.xsltFile = nonNullArgument(xsltFile, "xsltFile");
	}

	/**
	 * resolve an URI.
	 * 
	 * @param href the URI to resolve
	 * @param base the base URI (typically, <tt>null</tt> in the case of a
	 *            resource, but it can also be the original file's path in the
	 *            File System)
	 * @return the {@link Source} to import
	 */
	@Override
	public final Source resolve(
			final String href,
			final String base) throws TransformerException {

		nonNullArgument(href, "href");
		nonNullArgument(base, "base");

		final File basedir = xsltFile.getParentFile();

		final File file = new File(basedir, href);

		if (!file.exists()) {

			throw new TransformerException("Cannot find file: "
					+ file.getAbsolutePath() + " for URI: \"" + href + "\"");
		}

		return new StreamSource(file);
	}
}
